package com.huaxin.hxmodulesystem.service.impl;

import com.huaxin.hxmodulesystem.common.VerificationCodeGenerator;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.dto.request.SendSmsReqDTO;
import com.huaxin.hxmodulesystem.service.SmSService;
import com.huaxin.hxredis.common.RedisService;
import com.huaxin.message.sms.tencent.SmsService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Service
@RequiredArgsConstructor
public class SmSServiceImpl implements SmSService {
    private final Logger log = Logger.getLogger(SmSServiceImpl.class.getName());

    private final RedisService redisService;
    //腾讯云短信验证码的模版id
    @Value("${tencent.cloud.vCodeTemplateId}")
    private String vCodeTemplateId;

    private final SmsService smsService;
    private final VerificationCodeGenerator verificationCodeGenerator;

    //发送短信验证码
    @Override
    public ResponseResult<String> sendSmsVerificationCode(String phoneNumber) {
        String formattedPhoneNumber = smsService.formatPhoneNumber(phoneNumber);
        String verificationCode = verificationCodeGenerator.generateCode();
        String[] templateParams = {verificationCode};
        try {
            if (smsService.sendSms(formattedPhoneNumber, vCodeTemplateId, templateParams)) {
                SendSmsReqDTO reqDTO = new SendSmsReqDTO();
                reqDTO.setPhoneNumber(formattedPhoneNumber);
                reqDTO.setVerificationCode(verificationCode);
                redisService.setObject(formattedPhoneNumber, reqDTO, 3, TimeUnit.MINUTES);
            }
        } catch (TencentCloudSDKException e) {
            log.info("发送短信验证码异常！");
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "发送短信验证码异常！", null);
        }
        return ResponseResult.ok("发送成功！");
    }

    //验证短信验证码
    @Override
    public ResponseResult<String> verifySmsVerificationCode(String phoneNumber, String verificationCode) {
        String formattedPhoneNumber = smsService.formatPhoneNumber(phoneNumber);
        SendSmsReqDTO reqDTO = (SendSmsReqDTO) redisService.getObject(formattedPhoneNumber);
        if (reqDTO != null && reqDTO.getPhoneNumber().equals(formattedPhoneNumber) && reqDTO.getVerificationCode().equals(verificationCode)) {
            redisService.delete(phoneNumber);
            return ResponseResult.ok("验证成功！");
        } else {
            return ResponseResult.failure(ResponseCode.VERIFICATION_CODE_ERROR, "验证码错误！", null);
        }
    }
}
